package top.kent90.common.util;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;

public class Base64ToImage {

    private static Logger logger = LoggerFactory.getLogger(Base64ToImage.class);

    /**
     * 灏嗙綉缁滃浘鐗囨枃浠惰浆鍖栦负瀛楄妭鏁扮粍瀛楃涓诧紝骞跺鍏惰繘琛孊ase64缂栫爜澶勭悊
     *
     * @param imageUrl 鍥剧墖鐨剈rl璺緞锛屽http://.....xx.jpg
     * @return
     */
    public static String encodeUrlImageToBase64(URL imageUrl) {
        logger.info("imageUrl==" + imageUrl);
        ByteArrayOutputStream outputStream = null;
        try {
            BufferedImage bufferedImage = ImageIO.read(imageUrl);
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", outputStream);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        return Base64.getEncoder().encodeToString(outputStream.toByteArray());
    }

    /**
     * 灏嗘湰鍦板浘鐗囨枃浠惰浆鍖栦负瀛楄妭鏁扮粍瀛楃涓诧紝骞跺鍏惰繘琛孊ase64缂栫爜澶勭悊
     *
     * @param imageFile
     * @return
     */
    public static String encodeFileImageToBase64(File imageFile) {

        ByteArrayOutputStream outputStream = null;
        try {
            BufferedImage bufferedImage = ImageIO.read(imageFile);
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", outputStream);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        return Base64.getEncoder().encodeToString(outputStream.toByteArray());
    }

    /**
     * Base64浣嶇紪鐮佺殑鍥剧墖杩涜瑙ｇ爜锛屽苟淇濆瓨鍒版寚瀹氱洰褰�
     *
     * @param base64  base64缂栫爜鐨勫浘鐗囦俊鎭�
     * @param path    鎸囧畾鐩綍
     * @param imgName 鍥剧墖鍚嶇О
     */
    public static File decodeBase64ToImage(String base64, String path, String imgName) {
        FileOutputStream write = null;
        try {
            File file = new File(path + imgName);
            write = new FileOutputStream(file);
            byte[] decodeByte = Base64.getDecoder().decode(base64);
            write.write(decodeByte);
            write.flush();
            return file;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(write!=null)
                try {
                    write.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return null;
    }
}
